import { useState } from "react";
import codeBlockLess from "./codeBlock.module.less";
function CodeBlock({ node, inline, className, children, ...props }: any) {
  // 获取代码语言类型
  const match = /language-(\w+)/.exec(className || "");
  const language = match ? (match[1] === "vue" ? "javascript" : match[1]) : "";
  const [showCopy, setShowCopy] = useState(true);

  // 复制代码到剪贴板
  const handleCopy = () => {
    setShowCopy(false);
    const textContent = extractTextFromChildren(children);
    console.log("copy", children);
    navigator.clipboard.writeText(textContent.replace(/\n$/, "")); // 去掉结尾的换行
    console.log("赋值", textContent.replace(/\n$/, ""));
    setTimeout(() => {
      setShowCopy(true);
    }, 2000);
  };

  // 递归提取纯文本
  const extractTextFromChildren = (children: any): string => {
    let text = "";
    // 如果 children 是字符串或数字，直接返回
    if (typeof children === "string" || typeof children === "number") {
      text += String(children);
    } else if (Array.isArray(children)) {
      // 如果 children 是数组，递归处理每个元素
      children.forEach((child) => {
        text += extractTextFromChildren(child);
      });
    } else if (children && children.props && children.props.children) {
      // 处理 React 元素，递归提取它的子元素文本
      text += extractTextFromChildren(children.props.children);
    }

    return text;
  };

  return (
    <>
      {language ? (
        <div className={codeBlockLess.codeBlockContent}>
          {/* 代码类型和复制按钮 */}
          <div className="allTitle">
            <span>{language}</span>
            {showCopy ? (
              <div
                onClick={handleCopy}
                className="copy iconfont icon-fuzhi"
              ></div>
            ) : (
              <div className="copySuccess iconfont icon-wancheng"></div>
            )}
          </div>

          {/* 代码内容 */}
          <pre className="pre">
            <code className={className} {...props}>
              {children}
            </code>
          </pre>
        </div>
      ) : (
        children
      )}
    </>
  );
}

export default CodeBlock;
